import { updateUserMobileNumber, userGetPhoneNumber } from '../../../api/user'
import { sendValidCode } from '../../../api/base'
Page({
  data: {
    mobileNumber: '',
    verifyCode: '',
    isCountDown: false
  },

  onLoad: function (options) {
    this.setData({
      mobileNumber: options.key
    })
  },

  onblur(e) {
    this.setData({
      mobileNumber: e.detail.value
    })
  },


  changePhone({ detail = {} }) {
    this.setData({
      'mobileNumber': detail.value
    })
  },

  changeVerifyCode({ detail = {} }) {
    this.setData({
      'verifyCode': detail.value
    })
  },

  getPhoneNumber(e) {
    const _this = this
    wx.checkSession({
      success() {
        _this.setPhoneNumber(e.detail)
      },
      fail() {
        wx.login({
          success(res) {
            _this.setPhoneNumber(e.detail)
          }
        })
      }
    })
  },

  setPhoneNumber(detail) {
    userGetPhoneNumber({
      encryptedData: detail.encryptedData,
      iv: detail.iv
    }).then(res => {
      console.log(res)
      this.setData({
        'mobileNumber': res
      })
    })
  },

  getValidCode() {
    sendValidCode({
      phone: this.data.mobileNumber,
      bizTypeEnums: '手机绑定'
    }).then(res => {
      wx.showToast({
        title: '短信已发送'
      })
      this.countDownStart()
    })
  },

  countDownStart() {
    this.setData({
      isCountDown: true
    })
    const countDown = this.selectComponent('.control-count-down');
    countDown.start();
  },

  countDownReset() {
    // const countDown = this.selectComponent('.control-count-down');
    // countDown.reset();
    this.setData({
      isCountDown: false
    })
  },

  done(e) {
    const pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];
    updateUserMobileNumber({
      mobileNumber: this.data.mobileNumber,
      smsCode: this.data.verifyCode
    }).then(res => {
      prevPage.setData({
        'mobileNumber': this.data.mobileNumber
      })
      wx.navigateBack({
        delta: 1,
      })
    })
  }
})
